package com.windea.study.springcloud.zuul.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;

import java.io.*;

//自定义zuul熔断处理
//@Component
public class HelloFallbackProvider implements FallbackProvider {
	private final Logger logger = LoggerFactory.getLogger(HelloFallbackProvider.class);

	//指定要处理的 service。
	@Override
	public String getRoute() {
		return "spring-cloud-producer";
	}

	public ClientHttpResponse fallbackResponse() {
		return new ClientHttpResponse() {
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.OK;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				return 200;
			}

			@Override
			public String getStatusText() throws IOException {
				return "OK";
			}

			@Override
			public void close() {
			}

			@Override
			public InputStream getBody() throws IOException {
				return new ByteArrayInputStream("The service is unavailable.".getBytes());
			}

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_JSON);
				return headers;
			}
		};
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		if(cause != null && cause.getCause() != null) {
			String reason = cause.getCause().getMessage();
			logger.info("Exception {}", reason);
		}
		return fallbackResponse();
	}
}
